package com.kania.simpleemail.service;

import java.util.ArrayList;

import javax.mail.Folder;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;

import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import com.kania.simpleemail.core.IMAP;
import com.kania.simpleemail.data.EmailDBHelper;
import com.kania.simpleemail.data.MailData;

public class EmailService extends Service{
	
	private SharedPreferences accountInfo;
	private final String STRING_ACCOUNT_PREFERENCE_NAME = "account_info";
	
	private String sTag = "KANIA_LOG_SERVICE";
	boolean bNowRunning;
	Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			Bundle data = msg.getData();
			String str = data.getString("msg");
			Toast.makeText(EmailService.this, str, Toast.LENGTH_SHORT).show();
		}
	};
	
	private String sID;
	private String sPassword;
	private String sHost = "imap.gmail.com";
	

	@Override
	public void onCreate() {
		super.onCreate();
		accountInfo = this.getSharedPreferences(STRING_ACCOUNT_PREFERENCE_NAME, Activity.MODE_PRIVATE);
//		String sExistAccountList = accountInfo.getString("exist_account", "");
		sID = accountInfo.getString("exist_account", "");
		sPassword = accountInfo.getString("password", "");
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		super.onStartCommand(intent, flags, startId);
		
		//여기서 스레드 시작
		bNowRunning = false;
		MailRecvThread thread = new MailRecvThread(this, mHandler);
		thread.start();
		
		return START_STICKY;
		
	}
	
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	public void setAccountInfo (String _ID, String _password, String _host) {
		sID = _ID;
		sPassword = _password;
		sHost = _host;
	}
	

	class MailRecvThread extends Thread {
		EmailService mParent;
		Handler mHandler;
		
		
		
		public MailRecvThread (EmailService _parent, Handler _handler) {
			mParent = _parent;
			mHandler = _handler;
		}
		
		public void run() {
			//이메일 계정이 있는가 체크
			//test debug
			if ("".equals(sID)) {
				return;
			} //이거 문법상 맞는데 권장 사항인가?
			
			//각 이메일 계정마다
				//메일을 불러오도록 함
			
			//[130903] mutex 아닌 동기회 방법. 이후 동기화 기법을 사용하도록 한다. 

			Log.d(sTag, "FullSync Start");
			IMAP loginSession;
			ArrayList<MailData> alMailData = new ArrayList<MailData>();;
			
			
			try {
				//세션을 만들고 접근을 시도한 다음
//				loginSession = new IMAP(sHost, sID, sPassword);
				//[130828] changed by singleton parttern using [start]
				loginSession = IMAP.getInstance();
				loginSession.initIMAP(sHost, sID, sPassword);
				//[130828] changed by singleton parttern using [end]
				loginSession.open();
				
				//이 핸들러는 다른 핸들러가 되어야함
				//TODO mHandler 교체 요망
				loginSession.getMessages(alMailData, mHandler);
				Log.d(sTag, "get data of messages, message count = " + alMailData.size());
				
				
				//DB와 불러진 데이터를 비교한다.
				SQLiteDatabase DBCompMessage = (new EmailDBHelper(mParent)).getReadableDatabase();
				Cursor csMailData = DBCompMessage.rawQuery("SELECT uid FROM messages", null);
				while (csMailData.moveToNext()) {
					int nCompUID = csMailData.getInt(0);
					Log.d(sTag, "Compare of UID:" + nCompUID);
					for(MailData md: alMailData) {
						if (md.getUID() == nCompUID) {
							Log.d(sTag, "Remove same UID: " + nCompUID);
							//중복 uid에 대하여는 값을 -1로 놓는다. -1이면 db에 추가하지 않는다
							md.setUID(-1);
						}
					}
				}
				csMailData.close();
				DBCompMessage.close();
				
				SQLiteDatabase DBMessage = (new EmailDBHelper(mParent)).getWritableDatabase();
				//DB에 데이터를 저장한다.
				for (MailData md: alMailData) {
					//uid가 -1인 메일은 저장하지 않는다. 이후 사라짐.
					if(md.getUID() != -1){
						DBMessage.execSQL("INSERT INTO messages " +
								"(_id, account, uid, sender, receiver, cc, bcc, subject, date, contents) " + 
								"VALUES(null, '" + sID + "', '" 
								+ md.getUID() + "', '"
								+ md.getFromData() + "', '"
								+ md.getToData() + "', '"
								+ md.getCCData() + "', '"
								+ md.getBCCData() + "', '"
								+ md.getMailSubject() + "', '"
								+ md.getMailDate() + "', '"
								+ md.getContents() + "');");
					}
				}
				DBMessage.close();
				//메일을 한 번 받는 사이클마다 초기화한다.
				alMailData.clear();
				
			} catch (NoSuchProviderException e) {
				Log.e(sTag, "NoSuchProviderException");
				e.printStackTrace();
			} catch (MessagingException e) {
				Log.e(sTag, "MessagingException");
				e.printStackTrace();
			} finally {
				//TODO 수정하여야 함
//				endSession();
				Log.d(sTag, "FullSync have Finished");
			}
			
			
//			//now test
//			for (int i = 0; i < 10; i++) {
//
//				android.os.Message msg = android.os.Message.obtain();
//				Bundle data = new Bundle();
//				data.putString("msg", "test" + (i+1));
//				msg.setData(data);
//				msg.what = 0;
//				mHandler.sendMessage(msg);
//				
//				try {
//					Thread.sleep(3000);
//				} catch (InterruptedException e) {
//					e.printStackTrace();
//				}
//			}
		}
	}
}
